<template>
	<div class="ReadBook">
		<div class="book_title" :class="skinValue">
			<p>{{ chapter.cName }}</p>
			<p style="text-align: right">
				<van-loading v-if="refreshLoad" size="24px" color="#0094ff" style="margin-right: 20px;"></van-loading>
				<van-icon v-else name="replay" size="14" @click="toRefresh" style="margin-right: 10px;" />
				<van-icon name="revoke" size="14" @click="toHome" />
			</p>
		</div>
		<div v-if="readMode==0" ref="book_container" class="book_container" v-html="chapter.cContent" :style="{ fontSize: `${fontSize}px` }" :class="skinValue" @click="showopview"></div>
		<div v-if="readMode==1" class="book_content" @click="showopview" :style="{ fontSize: `${fontSize}px` }" :class="skinValue"
			ref="bookContent">
			
			<v-touch @swipeleft="swiperleft" @swiperight="swiperright">
				<!-- <p style="padding: 15px;line-height: 40px;min-height: 500px;">
					{{ contentData[current] }}
				</p> -->
				<p style="padding: 15px;line-height: 40px;min-height: 500px;" v-html="contentData[current]" >
				</p>
			</v-touch>
		</div>

		<div class="book_foot" :class="skinValue">
			<van-row>
				<van-col span="8">
					<van-button @click="GetBegin" :loading="beginLoad" :disabled="this.begin == 0" loading-text="加载中..."
						:class="skinValue" block>上一章</van-button>
				</van-col>
				<van-col span="8">
					<van-button @click="GetCatalogue" :loading="catalogueLoad" loading-text="加载中..." :class="skinValue"
						block>目录</van-button>
				</van-col>
				<van-col span="8">
					<van-button @click="GetEnd" :loading="endLoad" :disabled="this.end == -1" loading-text="加载中..."
						:class="skinValue" block>下一章</van-button>
				</van-col>
			</van-row>
		</div>
		<!-- 底部弹出层 打开目录和设置 -->
		<van-popup v-model="operationLoad" position="bottom" round>
			<van-field name="slider" label="翻页">
				<template #input>
					<van-radio-group v-model="readMode" direction="horizontal" @change="readModeChange">
						<van-radio :name="0">上下</van-radio>
						<van-radio :name="1">左右</van-radio>
					</van-radio-group>
				</template>
			</van-field>
			<van-field name="slider" label="字体大小">
				<template #input>
					<van-slider v-model="fontSize" min="12" max="30" @change="fontSizeChange"
						@drag-end="fontSizeChange" @input="fontSizeChange"/>
				</template>
			</van-field>
			<van-field name="checkbox" label="背景颜色">
				<template #input>
					<van-radio-group v-model="skinValue" direction="horizontal" class="van_radio_group_css" @change="skinCheckbox">
						<van-radio name="default" shape="square"></van-radio>
						<van-radio name="blue" shape="square"></van-radio>
						<van-radio name="green" shape="square"></van-radio>
						<van-radio name="light" shape="square"></van-radio>
						<van-radio name="night" shape="square"></van-radio>
					</van-radio-group>
				</template>
			</van-field>
		</van-popup>
		<van-popup id="cataLog" v-model="catalogueLoad" position="left" :style="{ width: '80%', height: '100%' }">
			<van-search v-model="search" @input="GetCatalogue" placeholder="请输入搜索关键词" />
			<van-list v-model="catalogueLoad" :finished="finished" finished-text="没有更多了">
				<van-cell :style="{color: item.cId==chapter.cId ? 'red':'#000'}" @click="onCatalogue(item.cId)" v-for="item in chapters" :key="item.cId" :title="item.cName" />
			</van-list>
		</van-popup>
	</div>
</template>
<script>
	import {
		getChapter,
		getFirst,
		getCatalogue1,
		getChapterRefresh
	} from "@/api/index.js";
	export default {
		name: "ReadBook",
		data() {
			return {
				begin: 0,
				end: -1,
				beginLoad: false,
				endLoad: false,
				catalogueLoad: false,
				// 操作显示状态
				operationLoad: false,
				// 默认字体大小 应该从数据库中取
				fontSize: 1.25,
				// 滑块初始值
				fontSizeSlider: 4,
				skinData: [{
						key: "default",
						checked: false
					},
					{
						key: "blue",
						checked: false
					},
					{
						key: "green",
						checked: false
					},
					{
						key: "light",
						checked: false
					},
					{
						key: "night",
						checked: false
					},
				],
				// 背景色默认样式
				skinValue: "default",

				finished: true,
				chapter: {
					cId: 0,
					bId: 0,
					cName: "",
					cContent: "",
					updateTime: "",
					url: "",
				},
				popupShow: false,
				chapters: [],
				search: "",
				current: 0, // 当前页码（下面数组索引），有缓存取缓存
				contentData: [], // 分页后数据
				totalPage: 1, // 总计多少页
				pageCount: 252, // 每页多少字
				readMode:0,//0:滚动，1：滑动
				refreshLoad:false
			};
		},
		mounted() {
			if (window.localStorage.getItem("myReadMode") != null)
				this.readMode = parseInt(window.localStorage.getItem("myReadMode"));
			// 初始化字体大小
			if (window.localStorage.getItem("myFontSize") != null)
				this.fontSize = window.localStorage.getItem("myFontSize");
			// if (window.localStorage.getItem("myFontSizeSlider") != null)
			// 	this.fontSizeSlider = parseInt(
			// 		window.localStorage.getItem("myFontSizeSlider")
			// 	);
			// 初始化背景
			if (window.localStorage.getItem("mySkinValue") != null) {
				this.skinValue = window.localStorage.getItem("mySkinValue");
			}

			this.chapter.bId = this.$route.query.bId;
			this.chapter.cId = this.$route.query.cId;
			if (this.chapter.cId == undefined || this.chapter.cId == null) {
				this.GetFirst();
			} else {
				this.GetChapter();
			}

			document.addEventListener('plusready', function() {
				var webview = plus.webview.currentWebview();
				plus.key.addEventListener('backbutton', function() {
					webview.canBack(function(e) {
						if(e.canBack) {
							webview.back();
						} else {
							webview.close(); //hide,quit
							//plus.runtime.quit();
						}
					})
				});
			});
		},
		methods: {
			GetChapter() {
				getChapter({
					id: this.chapter.cId,
				}).then((data) => {
					if (data.success) {
						this.chapter = data.response;

						this.seetingPage();

						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
						this.$nextTick(()=>{
							var data = document.getElementById('content');
							if(data!=null)
								data.scrollTop = window.localStorage.getItem('content_scrollTop_'+this.chapter.bId);
							data.addEventListener("scroll", this.onScroll);
						})
						

					}
				});
			},
			GetFirst() {
				getFirst({
					bId: this.chapter.bId,
				}).then((data) => {
					if (data.success) {
						this.chapter = data.response;

						// 第一页
						window.localStorage.setItem("pageId" + this.chapter.bId, 0);
						this.seetingPage();

						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
						this.$nextTick(()=>{
							var data = document.getElementById('content');
							if(data!=null)
								data.scrollTop = window.localStorage.getItem('content_scrollTop_'+this.chapter.bId);
							data.addEventListener("scroll", this.onScroll);
						})
					}
				});
			},
			GetBegin() {
				this.chapter.cId = this.begin;
				this.beginLoad = true;
				getChapter({
					id: this.chapter.cId,
				}).then((data) => {
					this.beginLoad = false;
					if (data.success) {
						this.chapter = data.response;

						// 第一页
						window.localStorage.setItem("pageId" + this.chapter.bId, 0);
						this.seetingPage();

						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
						this.$nextTick(()=>{
							var data = document.getElementById('content');
							window.localStorage.setItem('content_scrollTop_'+this.chapter.bId,0);
							if(data!=null)
								data.scrollTop = window.localStorage.getItem('content_scrollTop_'+this.chapter.bId);
							data.addEventListener("scroll", this.onScroll);
						})
					}
				});
			},
			GetEnd() {
				this.chapter.cId = this.end;
				this.endLoad = true;
				getChapter({
					id: this.chapter.cId,
				}).then((data) => {
					this.endLoad = false;
					if (data.success) {
						this.chapter = data.response;

						// 第一页
						window.localStorage.setItem("pageId" + this.chapter.bId, 0);
						this.seetingPage();

						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
						this.$nextTick(()=>{
							var data = document.getElementById('content');
							window.localStorage.setItem('content_scrollTop_'+this.chapter.bId,0);
							if(data!=null)
								data.scrollTop = window.localStorage.getItem('content_scrollTop_'+this.chapter.bId);
							data.addEventListener("scroll", this.onScroll);
						})
					}
				});
			},
			GetCatalogue() {
				this.catalogueLoad = true;
				getCatalogue1({
					page: 1,
					bId: this.chapter.bId,
					cName: this.search,
					intPageSize: 100000,
				}).then((data) => {
					if (data.success) {
						this.chapters = data.response.data;
					}
					if(this.search==''){
						this.$nextTick(()=>{
							var ac=0;
							for (let index = 0; index < this.chapters.length; index++) {
								const c = this.chapters[index];
								if(c.cId==this.chapter.cId){
									ac=index;
								}
							}
							var data = document.getElementById('cataLog');
							if(data!=null)
								data.scrollTop=50+44*ac;
						})
					}
				});
			},
			onCatalogue(cId) {
				this.popupShow = false;
				this.catalogueLoad = true;
				getChapter({
					id: cId,
				}).then((data) => {
					if (data.success) {
						this.catalogueLoad = false;
						this.chapter = data.response;

						// 第一页
						window.localStorage.setItem("pageId" + this.chapter.bId, 0);
						this.seetingPage();

						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
					}
				});
			},
			toHome() {
				this.$nextTick(()=>{
					var data = document.getElementById('content');
					if(data!=null)
						window.localStorage.setItem('content_scrollTop_'+this.chapter.bId,data.scrollTop);
				})
				this.$router.push({
					path: "/"
				});
			},
			onScroll(){
				var data = document.getElementById('content');
				if(data!=null)
					window.localStorage.setItem('content_scrollTop_'+this.chapter.bId,data.scrollTop);
			},
			// 分页
			seetingPage() {
				var _content = this.chapter.cContent
					.replace(/<[^>]*>/g)
					.replace(new RegExp("undefined", "g"), "")
					.replace(new RegExp("\r", "g"), "")
					.replace(new RegExp("&nbsp;", "g"), "")

				// 总页码
				if (_content.length % this.pageCount == 0) {
					this.totalPage = parseInt(_content.length / this.pageCount);
				} else {
					this.totalPage = parseInt(_content.length / this.pageCount) + 1;
				}

				var _contentData = [];
				// 填充数组
				for (var i = 0; i < this.totalPage; i++) {
					_contentData.push(
						_content.slice(i * this.pageCount, (i + 1) * this.pageCount)
					);
				}
				this.contentData = _contentData;
				// 获取上次浏览位置
				var _cachePage = window.localStorage.getItem("pageId" + this.chapter.bId);
				// 跳转到上次浏览位置
				if (_cachePage != null) {
					this.current = parseInt(_cachePage)
				}
			},
			//打开底部的操作菜单
			showopview() {
				this.operationLoad = true;
			},
			readModeChange(){
				window.localStorage.setItem("myReadMode", this.readMode);
			},
			// 设置字体大小
			fontSizeChange(num) {
				// this.fontSize = 0.875 + (num - 1) * 0.125;

				// 存入数据库
				window.localStorage.setItem("myFontSize", this.fontSize);
				// window.localStorage.setItem("myFontSizeSlider", num);
			},
			// 设置背景色
			skinCheckbox() {
				// let items = this.skinData;
				// items.forEach((_item) => {
				// 	_item.checked = false;
				// });

				// this.skinData[index].checked = true;
				// this.skinValue = key;
				// console.log(key);

				// 存入数据库
				window.localStorage.setItem("mySkinValue", this.skinValue);
			},
			swiperleft: function() {
				if (this.current +1 < this.totalPage){
					this.current += 1
					// 存储
					window.localStorage.setItem("pageId" + this.chapter.bId, this.current);
				}else{
					// console.log("下一章")
					// this.GetEnd()
				}
				
			},
			swiperright: function() {
				if (this.current > 0){
					this.current -= 1
					// 存储
					window.localStorage.setItem("pageId" + this.chapter.bId, this.current);
				}else{
					// console.log("上一章")
					// this.GetBegin()
				}
					
			},
			toRefresh(){
				this.refreshLoad=true;
				getChapterRefresh({
					cId:this.chapter.cId
				}).then((data) => {
					this.refreshLoad=false;
					if (data.success) {
						this.chapter = data.response;
						this.seetingPage();
						this.begin = parseInt(data.msgDev.split("|")[0]);
						this.end = parseInt(data.msgDev.split("|")[1]);
						window.localStorage.setItem(
							"cId" + this.chapter.bId,
							this.chapter.cId
						);
					}
				});
			}
		},
	};
</script>
<style lang="scss" scoped>
	.ReadBook {
		height: 100%;
		width: 100%;
		position: relative;
		overflow: hidden;

		// background: #ccbda0;
		.book_title {
			position: fixed;
			z-index: 10;
			width: 100%;

			// background: #ccbda0;
			p {
				font-size: 12px;
				padding-left: 10px;
				margin: 0;
				line-height: 28px;
				height: 28px;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
				width: calc(50% - 20px);
				float: left;
			}
		}
		.book_container{
			height: calc(100% - 70px);
			padding: 0px;
			margin-top: 28px;
			position: fixed;

			// background: #ccbda0;
			/deep/ div {
				overflow: scroll;
				height: 100%;
				padding: 0 10px;
				//background: #ccbda0;
			}
		}
		.book_content {
			height: calc(100% - 70px);
			padding: 0px;
			margin-top: 28px;
			position: fixed;

			// background: #ccbda0;
			/deep/ div {
				overflow: scroll;
				// height: 100%;
				// padding: 0 10px;
				// background: #ccbda0;
			}
		}

		.book_foot {
			position: fixed;
			bottom: 0px;
			// z-index: 10;
			width: 100%;

			// background: #ccbda0;
			p {
				font-size: 14px;
				padding-left: 10px;
				margin: 0;
				line-height: 32px;
				height: 32px;
				text-align: center;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}

			/deep/ .van-button--block {
				border: none;
			}
		}
	}

	.chcekbutton {
		// float: left;
		width: 50px;
		height: 35px;
		display: inline-block;
		line-height: 50px;
		margin-left: 5px;
	}

	.default {
		/* background: #C3B297; */
		background: #ccbda0;
	}

	.blue {
		background: #cad9e8;
	}

	.green {
		background: #d1edd1;
	}

	.light {
		background: #e6e6e6;
	}

	.night {
		color: #cad9e8;
		background: #1a1a1a;
	}
	.van_radio_group_css{
		/deep/ .van-radio:first-child .van-icon{
			background: #ccbda0;
		}
		/deep/ .van-radio:nth-child(2) .van-icon{
			background: #cad9e8;
		}
		/deep/ .van-radio:nth-child(3) .van-icon{
			background: #d1edd1;
		}
		/deep/ .van-radio:nth-child(4) .van-icon{
			background: #e6e6e6;
		}
		/deep/ .van-radio:nth-child(5) .van-icon{
			background: #1a1a1a;
		}
	}
	.van-nav-bar {
		background: #ccbda0;

		// 因为style标签上有 lang='less'  所以.van-nav-bar__title 可以嵌套到.van-nav-bar里面
		/* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
		/deep/ .van-nav-bar__title {
			color: white;
		}
	}

	.book_content {
		/deep/ .van-swipe-item {
			// min-width: 330px;
			line-height: 40px;
		}
	}
</style>
